package com.huan.springcloud;

import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.MessageQueueSelector;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageQueue;
import org.apache.rocketmq.spring.autoconfigure.RocketMQProperties;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

public class Send {

    public static void main(String[] args) throws Exception {
//        String topic = "MarketingActivMercRelationGroup";
        String topic = "test";
        DefaultMQProducer producer = new DefaultMQProducer(topic);

//        producer.setNamesrvAddr("10.213.32.177:9876;10.213.32.178:9876");
        producer.setNamesrvAddr("192.168.56.100:9876");
//        producer.setNamesrvAddr("paidmq-namesvr01.yspos-fat.com");

        producer.start();

//        String[] tags = new String[]{"TagA", "TagC", "TagD"};

        // 订单列表
//       List<OrderStep> orderList = new RocketMQProperties.Producer().buildOrders();

        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateStr = sdf.format(date);
        for (int i = 0; i < 10; i++) {
            // 加个时间前缀
            String body = dateStr + " Hello RocketMQ ";
            Message msg = new Message("MarketingActivMercRelationTopic", "KEY" + i, body.getBytes());

            SendResult sendResult = producer.send(msg, new MessageQueueSelector() {
                @Override
                public MessageQueue select(List<MessageQueue> mqs, Message msg, Object arg) {
//                    Long id = (Long) arg;  //根据订单id选择发送queue
//                    long index = id % mqs.size();
                    String mercId = (String) arg;
                    long index = (mercId.hashCode() & Integer.MAX_VALUE) % mqs.size();
                    System.out.println(mqs.size()+"==index========="+index);
                    return mqs.get((int)index);
                }
            }, "826102115200010");//订单id

            System.out.println(String.format("SendResult status:%s, queueId:%d, body:%s",
                    sendResult.getSendStatus(),
                    sendResult.getMessageQueue().getQueueId(),
                    body));
        }

        producer.shutdown();
    }
}
